var _UPLOAD_BUCKET_GOODS = 116;
var _UPLOAD_VIEW_TYPE_3 = 'view3';
var _BASE_IMAGE_URL='http://s3s.lecloud.com/9xi-user-'+_UPLOAD_VIEW_TYPE_3 + '/';

//商家状态
var _STATUS_DICT = {
	item: [
	    {id:'' , text: '全部'},
	    {id: 13, text: '可用'},
	    {id: 14, text: '停用'},
	    {id: 15, text: '锁定'}
	],
	itemb: [
	    {id: 13, text: '可用'},
	    {id: 14, text: '停用'},
	    {id: 15, text: '锁定'}
	],
	data: {
	    '13': '可用',
	    '14': '停用',
	    '15': '锁定'
	}	
};
//合同状态
var _CONTRACTSTATUS_DICT = {
	item: [
	    {id:'' , text: '全部'},
	    {id: 22, text: '审核中'},
	    {id: 23, text: '审核通过'},
	    {id: 24, text: '审核不通过'}
	],
	itemb: [
	    {id: 22, text: '审核中'},
	    {id: 23, text: '审核通过'},
	    {id: 24, text: '审核不通过'}
	],data: {
	    '22': '审核中',
	    '23': '审核通过',
	    '24': '审核不通过'
	}	
};
//商家类型
var _MERCHANTTYPE_DICT = {
	item: [
	    {id:'' , text: '全部'},
	    {id: 151, text: '自营'},
	    {id: 152, text: '非自营'}
	],
	itemb: [
	    {id: 151, text: '自营'},
	    {id: 152, text: '非自营'}
	],data: {
	    '151': '自营',
	    '152': '非自营'
	}	
};
//商家金价类型
var _GOLDPRICEJSON_DICT = {
	item: [
	    {id:'' , text: '全部'},
	    {id: 165, text: '投资金'},
	    {id: 166, text: '公益金'},
	    {id: 167, text: '收益金'}
	],
	itemb: [
	    {id: 165, text: '投资金'},
	    {id: 166, text: '公益金'},
	    {id: 167, text: '收益金'}
	],
	itemc: [
	    {id: 165, name: '投资金'},
	    {id: 166, name: '公益金'},
	    {id: 167, name: '收益金'}
	],data: {
	    '165': '投资金',
	    '166': '公益金',
	    '167': '收益金'
	}	
};

var win_width = 936;
var win_height = 490;
//宽度适应屏幕分辨率的变化
if (screen.width >= 1280){
    win_width = 936;
}else{
    win_width = screen.width-300;
}
var datagrid;
//初始化
$(function(){
//会员列表
datagrid = $('#datagrid_data').datagrid({
	url: root + 'merchant/merchantList',
	singleSelect: true,
	striped : true,
	fitColumns : false,
	border : false,
	showFooter: false,
	idField : 'merchantId',
	rownumbers : true,
	pagination : true,
	pagePosition : 'bottom',
    //自适应列
    columns : [ [ {
      title : '商家ID',
      field : 'merchantId',
      align: 'center',
      width : 120
    }, {
        title : '联系电话',
        field : 'contactMobile',
        align: 'center',
        width : 120
    }, {
        title : '联系人名称',
        field : 'contactName',
        align: 'center',
        width : 120
    }, {
        title : '固定电话',
        field : 'telephone',
        align: 'center',
        width : 120
    }, {
        title : '公司名称',
        field : 'companyName',
        align: 'center',
        width : 120
    }, {
        title : '公司网站',
        field : 'companyWeb',
        align: 'center',
        width : 120
    }, {
        title : '公司类型',
        field : 'merchantType',
        align: 'center',
        width : 120,
        formatter: formatDict('merchantType')
    }, {
        title : '状态',
        field : 'status',
        align: 'center',
        width : 120,
        formatter: formatDict('status')
    } ] ],
    toolbar:[{
	    text : '详情',
	    iconCls: 'icon-search',
	    handler: function(){
	    	var row = $('#datagrid_data').datagrid('getSelected');
            if (row) {
                detail($('#datagrid_data').datagrid('getRowIndex', row));
            } else {
                showmsg('请选择后进行查看!');
                return false;
            }
	    }
	  },{
	    text : '添加',
	    iconCls: 'icon-add',
	    handler: function(){
	        addEdit(null);
	    }
	  },{
	    text : '编辑',
	    iconCls: 'icon-edit',
	    handler: function(){
	    	var row = $('#datagrid_data').datagrid('getSelected');
            if (row) {
            	addEdit($('#datagrid_data').datagrid('getRowIndex', row));
            } else {
                showmsg('请选择后进行编辑!');
                return false;
            }
	    }
	} ]
  });
  //商家详情
  $('#win_detail').window({
	  title: '商家详情',
	  width: win_width,
      height: win_height,
      top: ($(window).height() - win_height) * 0.5,
      left: ($(window).width() - win_width) * 0.5,
      shadow: true,
      modal: true,
      closed: true,
      minimizable: false,
      maximizable: true,
      collapsible: false,
      center: true,
      onBeforeClose: function(){
    	 $('#win_detail').scrollTop(0);
    	 $('#win_detail span').empty();
      }
  });
  //添加, 编辑
  $('#win_addEdit').window({
	  width: win_width,
	  height: win_height,
	  top: ($(window).height() - win_height) * 0.5,
	  left: ($(window).width() - win_width) * 0.5,
	  shadow: true,
	  modal: true,
	  closed: true,
	  minimizable: false,
	  maximizable: true,
	  collapsible: false,
	  center: true,
	  onBeforeClose: function(){
		  $('#win_addEdit').scrollTop(0);
	  },
	  onClose: function(){
		  $('#certificateImagea_ad').siblings('img').remove();
		  $('#certificateImageb_ad').siblings('img').remove();
	  }
  });
  //图片上传
  $('#certificateImagea_ad').filebox({
	 buttonText: '证件正面',
	 onChange: function(newValue, oldValue){
		 if(newValue == oldValue){
			 return;
		 }
		 uploadImg('certificateImagea_ad');
	 }
  });
  $('#certificateImageb_ad').filebox({
	  buttonText: '证件背面',
	  onChange: function(newValue, oldValue){
		  if(newValue == oldValue){
				 return;
		  }
		  uploadImg('certificateImageb_ad');
	  }
  });

});
//-------------初始化结束--------------
//搜索
function searchMerchant(){
	datagrid.datagrid({
		url: root + 'merchant/merchantList',
		queryParams:{
			merchantId: $('#merchantId').val(),
			companyName: $('#companyName').val(),
			contactMobile: $('#contactMobile').val()
		}
	});
}
//重置
function searchClean(){
	$('#merchantId').textbox('reset');
	$('#companyName').textbox('reset');
	$('#contactMobile').textbox('reset');
}
//图片上传
function uploadImg(fileId, viewImgId){
	var realFileId = $($($('#'+fileId).siblings('span')[0]).children('input[type="file"]')[0]).attr('id');
	if($('#'+fileId).filebox('getValue').length <= 0){
		return;
	}
	$.ajaxFileUpload({
		url: root + 'upload/uploadImage',
		fileElementId: realFileId,
		dataType: 'json',
		type: 'post',
		data: {
			bucketId: _UPLOAD_BUCKET_GOODS,
			viewType: _UPLOAD_VIEW_TYPE_3
		},
		success: function(data, status){
			if(data.error == 0){
				$('#'+fileId).siblings('img').remove();
				$('#'+fileId).before('<img alt="" src="'+data.url+'">');
				$('#'+fileId+'_imageName').attr('value', data.url);
			}else{
				showmsg("图片上传失败!");
			}
		},
		error: function(data, status, e){
			showmsg("图片上传失败!");
		}
	});
}
//初始化添加或编辑
function initForm(){
	  $('#addEditForm').form('clear');
	  //合同状态
	  $("#contractStatus_ad").combobox({
		  valueField: 'id',
		  textField: 'text',
		  editable: false,
		  data: _CONTRACTSTATUS_DICT.itemb
	  }).combobox('setValue', '22');
	  //商家类型
	  $('#merchantType_ad').combobox({
		  valueField: 'id',
		  textField: 'text',
		  editable: false,
		  data: _MERCHANTTYPE_DICT.itemb
	  }).combobox('setValue', '151');
	  //商家状态下拉选
	  $('#status_ad').combobox({
		  valueField: 'id',
		  textField: 'text',
		  editable: false,
		  data: _STATUS_DICT.itemb
	  }).combobox('setValue', '13');
}
//打开添加或编辑窗口
function addEdit(rowIndex){
	$.fn.validatebox.defaults.rules.remote.message = '该登录名已存在, 请更换其他名称.';
	initForm();
	if(rowIndex == null){
		//添加
		$('#win_addEdit').window({
			title: '新增商家'
		});
	}else{
		//编辑
		$('#win_addEdit').window({
			title: '编辑商家'
		});
		var rows = datagrid.datagrid('getRows');
		var rowData = rows[rowIndex];
	    $('#merchantId_ad').attr('value', rowData.merchantId);
	    $('#contactName_ad').textbox('setValue', rowData.contactName);
	    $('#contactMobile_ad').textbox('setValue', rowData.contactMobile);
	    $('#telephone_ad').textbox('setValue', rowData.telephone);
	    $('#email_ad').textbox('setValue', rowData.email);
	    $('#status_ad').combobox('setValue', rowData.status);
	    $('#companyName_ad').textbox('setValue', rowData.companyName);
	    $('#companyWeb_ad').textbox('setValue', rowData.companyWeb);
	    $('#merchantType_ad').combobox('setValue', rowData.merchantType);
	    $('#legalName_ad').textbox('setValue', rowData.legalName);
	    $('#certificateType_ad').textbox('setValue', rowData.certificateType);
	    $('#certificateNo_ad').textbox('setValue', rowData.certificateNo);
	    if(rowData.certificateImagea != null && rowData.certificateImagea != ''){
			$('#certificateImagea_ad').before('<img alt="证件正面" src="'+rowData.certificateImagea+'">');
		}
		if(rowData.certificateImageb != null && rowData.certificateImageb != ''){
			$('#certificateImageb_ad').before('<img alt="证件背面" src="'+rowData.certificateImageb+'">');
		}
	    $('#certificateBegin_ad').textbox('setValue', dateFormat(rowData.certificateBegin));
	    $('#certificateExpiry_ad').textbox('setValue', dateFormat(rowData.certificateExpiry));
	    $('#contractNo_ad').textbox('setValue', rowData.contractNo);
	    $('#contractContent_ad').textbox('setValue', rowData.contractContent);
	    $('#contractStatus_ad').combobox('setValue', rowData.contractStatus);
	    $('#bankName_ad').textbox('setValue', rowData.bankName);
	    $('#bankNo_ad').textbox('setValue', rowData.bankNo);
	    $('#remark_ad').textbox('setValue', rowData.remark);
	    //黄金价格
	    if(rowData.goldPriceJson != null && rowData.goldPriceJson != ''){
	    	var goldPriceArr = JSON.parse(rowData.goldPriceJson);
	    	for(var i=0; i<goldPriceArr.length; i++){
	    		var obj = goldPriceArr[i];
	    		if(obj.price != null){
	    			$('#gold_price_ad_'+obj.id).textbox('setValue', parseFloat(obj.price)/100);
	    		}
	    	}
	    }
	}
	$('#win_addEdit').css("display","block");
	$('#win_addEdit').window('open');
}
//关闭添加或编辑窗口
function closeAddEditWin(){
	$('#win_addEdit').window('close');
}
//表单提交
function submitAddEditForm(){
    if ($('#addEditForm').form('validate')){
    	load();
        var dataPara = getFormJson($('#addEditForm'));
        var goldPriceArr = new Array();
        for(var i=0; i<_GOLDPRICEJSON_DICT.itemc.length; i++){
          var id = _GOLDPRICEJSON_DICT.itemc[i].id;
      	  if(dataPara[id] !== undefined && dataPara[id] != null && dataPara[id] != ''){
      		  var goldPriceObj = _GOLDPRICEJSON_DICT.itemc[i];
      		  goldPriceObj.price = parseFloat(dataPara[id]) * 100;
      		  goldPriceArr.push(goldPriceObj);
      	  }
        }
        if(goldPriceArr.length > 0){
        	var goldPriceJson = JSON.stringify(goldPriceArr);
        	dataPara.goldPriceJson = goldPriceJson;
        }else{
        	dataPara.goldPriceJson = null;
        }
        var url = root + 'merchant/addOrUpdate';
        $.post(url, dataPara, function (data) {
        	disLoad();
            if (data.errcode == 0) {
            	closeAddEditWin();
                showmsg(data.errmsg);
                datagrid.datagrid('reload');
            } else {
                showmsg(data.errmsg);
            }
        }).error(function () {
            showmsg('操作失败！');
            disLoad();
        });
    }
}
//商家详情
function detail(rowIndex){
	var rows = datagrid.datagrid('getRows');
    var rowData = rows[rowIndex];
    $('#merchantId_dl').text(rowData.merchantId);
    $('#contactName_dl').text(rowData.contactName);
    $('#contactMobile_dl').text(rowData.contactMobile);
    $('#telephone_dl').text(rowData.telephone);
    $('#email_dl').text(rowData.email);
    $('#status_dl').text(_STATUS_DICT.data[rowData.status]);
    $('#companyName_dl').text(rowData.companyName);
    $('#companyWeb_dl').text(rowData.companyWeb);
    $('#merchantType_dl').text(_MERCHANTTYPE_DICT.data[rowData.merchantType]);
    $('#legalName_dl').text(rowData.legalName);
    $('#certificateType_dl').text(rowData.certificateType);
    $('#certificateNo_dl').text(rowData.certificateNo);
    if(rowData.certificateImagea != null && rowData.certificateImagea != ''){
		$('#certificateImagea_dl').append('<img alt="证件正面" src="'+rowData.certificateImagea+'">');
	}
	if(rowData.certificateImageb != null && rowData.certificateImageb != ''){
		$('#certificateImageb_dl').append('<img alt="证件背面" src="'+rowData.certificateImageb+'">');
	}
    if(rowData.certificateBegin != null && rowData.certificateExpiry != null){
    	var expiry = dateFormat(rowData.certificateBegin) + '  至  ' + dateFormat(rowData.certificateExpiry);
    	$('#certificateExpiry_dl').text(expiry);
    }
    $('#contractNo_dl').text(rowData.contractNo);
    $('#contractContent_dl').text(rowData.contractContent);
    $('#contractStatus_dl').text(_CONTRACTSTATUS_DICT.data[rowData.contractStatus]);
    $('#bankName_dl').text(rowData.bankName);
    $('#bankNo_dl').text(rowData.bankNo);
    $('#createTime_dl').text(datetimeFormat(rowData.createTime));
    $('#remark_dl').text(rowData.remark);
    //黄金价格
    if(rowData.goldPriceJson != null && rowData.goldPriceJson != ''){
    	var goldPriceArr = JSON.parse(rowData.goldPriceJson);
    	for(var i=0; i<goldPriceArr.length; i++){
    		var obj = goldPriceArr[i];
    		$('#gold_price_dl_'+obj.id).text((parseFloat(obj.price)/100)+' 元/g');
    	}
    }
    
    $('#win_detail').css("display","block");
	$('#win_detail').window('open');
}
//密码重置
function resetPwd(rowData){
	if(rowData){
		var url = root + 'merchant/resetPwd';
        $.post(url, {
        	merchantId: rowData.merchantId,
        	loginName: rowData.loginName
        }, function (data) {
        	disLoad();
            if (data.errcode == 0) {
                showmsg(data.result);
            } else {
                showmsg(data.errmsg);
            }
        }).error(function () {
            showmsg('操作失败！');
            disLoad();
        });
	}else{
		showmsg('请选择一行后进行操作!')
		return false;
	}
}

//------formatter------
function formatDict(field) {
    return function (value, row, index) {
        var data = eval('_' + field.toUpperCase() + '_DICT');
        if (value && data.data && data.data.hasOwnProperty(value)) {
            return data.data[value];
        }
        return value;
    }
}
function dateFormat(value, rowData, rowIndex){
	if(value && typeof(value)!="undefined"){
		return new Date(value).format("yyyy-MM-dd");
	}else{
		return '';
	}
}
function datetimeFormat(value, rowData, rowIndex){
	if(value && typeof(value)!="undefined"){
		return new Date(value).format("yyyy-MM-dd hh:mm:ss");
	}else{
		return '';
	}
}

